package com.piesat.quake.common.mqtt.decoder;

import com.piesat.quake.common.mqtt.decoder.common.CommonDecoder;
import com.piesat.quake.common.mqtt.decoder.entity.WcData;
import com.piesat.quake.common.mqtt.decoder.entity.WcDataPc;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class WcDataDecoder extends CommonDecoder<WcData> {

    public WcDataDecoder(byte[] bytes) {
        super(bytes);
    }

    @Override
    public WcData decoder() {
        //读取基础信息
        WcData data = new WcData();
        data.setType(this.readString(2));
        data.setLength(this.readIntegerLE());
        data.setId(this.readString(8));
        data.setEndian(this.readByte());
        data.setTimestamp(Double.valueOf(this.readDoubleLE()*1000.0).longValue());

        data.setNum(this.readIntegerLE());
        data.setNetworkNo(this.readString(2));
        data.setLocation(this.readString(2));
        data.setCid(this.readByte());
        data.setSampleSize(this.readIntegerLE());
        data.setSampleRate(this.readIntegerLE());
        data.setKey(data.getId() + "_" + data.getTimestamp());

        List<WcDataPc> pcList = new ArrayList<>();
        byte flag = 1;
        Class<? extends WcDataPc> aClass = WcDataPc.class;
        while (flag > 0) {
            WcDataPc dataPc = new WcDataPc();
            dataPc.setNo(this.readByte());
            dataPc.setNextNo(this.readByte());
            flag = dataPc.getNextNo();
            dataPc.setLength(this.readIntegerLE());
            dataPc.setChId(this.readByte());
            dataPc.setStatus(this.readByte());
            int start=8;
            int length=dataPc.getLength();
            length = Math.min((length - start) / 4,50);
            for (int i = 0; i < length; i++) {
                try {
                    Field field = aClass.getDeclaredField("val" + i);
                    field.setAccessible(true);
                    field.set(dataPc, this.readFloatLE());
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            pcList.add(dataPc);
        }
        data.setPcList(pcList);
        return data;
    }
}
